/*
 * Created on Feb 24, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.mortbay.http.HttpServer;

import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.db.IDBConnection;

import edu.mit.simile.longwell.corpus.Corpus;
import edu.mit.simile.longwell.ui.Flair;
import edu.mit.simile.longwell.ui.FlairLocalProfile;
import edu.mit.simile.longwell.ui.FlairServlet;

/**
 * @author dfhuynh
 */
public class Main {
    static private Logger s_logger;
   
    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("Expecting a properties file as argument");
            System.exit(1);
        }

        URL log4jPropertiesFileURL = Main.class.getResource("log4j.properties");
        PropertyConfigurator.configure(log4jPropertiesFileURL);

        s_logger = Logger.getLogger(Main.class);
        
        /*
         * Read configuration property files
         */
        Properties properties = new Properties();
        try {
            File propertiesFile = new File(args[0]);

            s_logger.info("Reading properties file " + propertiesFile.getCanonicalPath());

            FileInputStream fis = new FileInputStream(propertiesFile);

            properties.load(fis);

            fis.close();
        } catch (Exception e) {
            s_logger.error("Failed to read properties file", e);
            System.exit(1);
        }
        
        /*
         * Set defaults
         */
        {
        	String language = properties.getProperty("defaults.locale.language");
        	String country = properties.getProperty("defaults.locale.country");
        	String variant = properties.getProperty("defaults.locale.variant");
        	if (language != null) {
        		if (country != null) {
        			if (variant != null) {
        				Locale.setDefault(new Locale(language, country, variant));
        			} else {
        				Locale.setDefault(new Locale(language, country));
        			}
        		} else {
        			Locale.setDefault(new Locale(language));
        		}
        	}
        	
        	String timeZone = properties.getProperty("defaults.timeZone");
        	if (timeZone != null) {
        		TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
        	}
        }

        /*
         * Create default corpus
         */

        Corpus corpus = null;
        try {
        	Properties properties2 = new Properties();
        	
        	properties2.put("directory", properties.getProperty("defaultCorpus.dir"));
        	properties2.put("database", properties.getProperty("defaultCorpus.database"));
        	properties2.put("modelName", properties.getProperty("defaultCorpus.modelName"));
        	
            corpus = Corpus.createCorpus(
                "urn:edu.mit.simile:object:defaultCorpus",
                properties.getProperty("defaultCorpus.connector"),
                properties2);
        } catch (Exception e) {
            s_logger.error("Failed to create default corpus", e);
            System.exit(1);
        }

        /*
         * Start up longwell server
         */

        LongwellServer longwellServer = null;
        try {
            longwellServer = new LongwellServer(
                corpus,
                new File(properties.getProperty("defaultCorpus.systemDir")),
                new File(properties.getProperty("commonSystemDir"))) {
            	
                protected Profile createDefaultProfile(
                        Corpus corpus, File structuredModelsDir) {
                    return new FlairLocalProfile(
                        "default", corpus, structuredModelsDir);
                }
            };

        } catch (Exception e) {
            s_logger.error("Failed to create longwell server", e);
            System.exit(1);
        }
    	
    	 /*
         * Create HTTP server
         */
        HttpServer httpServer = null;
        try {
            httpServer = Flair.createWebServer(
                new File(properties.getProperty("server.resourcePath", "./src/ui")),
                properties.getProperty("server.host", null),
                properties.getProperty("server.contextPath", "/longwell"),
                FlairServlet.class,
                Integer.parseInt(properties.getProperty("server.port", "8888")));

                Runtime.getRuntime().addShutdownHook(new Thread() {
                LongwellServer 	m_longwellServer;
                HttpServer		m_httpServer;

                public void run() {
                    try {
                        m_longwellServer.dispose();
                        m_httpServer.stop(true);
                    } catch (InterruptedException e) {
                        s_logger.error("Failed to stop HTTP server", e);
                    }
                }

                public Thread init(HttpServer httpServer, LongwellServer longwellServer) {
                    m_httpServer = httpServer;
                    m_longwellServer = longwellServer;
                    return this;
                }
            }.init(httpServer, longwellServer));
        } catch (Exception e) {
            longwellServer.dispose();

            s_logger.error("Failed to create web server", e);
            System.exit(1);
        }

        /*
         * Start the HTTP server
         */
        try {
            httpServer.start();
            httpServer.setStopGracefully(true);
        } catch (Exception e) {
            s_logger.error("Failed to start web server", e);
            System.exit(1);
        }
    }
}
